<template>
  <div id="productsManager">
    <el-row class="header" type="flex" align="middle" justify="end">
      <el-col class="paramsPanel">
        <el-row type="flex" align="middle">
          <span id="headTitle">商品中心</span>
          <el-button @click="dialogFormVisible = true;" size="small" type="primary" style="font-size: 20px;"><i class="el-icon-circle-plus"></i></el-button>
          <!-- 添加商品模态框 -->
          <el-dialog title="添加商品" :visible.sync="dialogFormVisible">
            <el-form ref="addProdForm" :model="addProduct" label-position="right" label-width="100px" size="small">
              <el-form-item label="商品名称" prop="productName">
                <el-input v-model="addProduct.productName" autocomplete="off" placeholder="商品名"></el-input>
              </el-form-item>
              <el-row type="flex">
                <el-col style="text-align: center;" :span="12">
                  <el-form-item label="价格" style="width: 100%;" prop="productPrice">
                    <el-input-number v-model="addProduct.productPrice"></el-input-number>
                  </el-form-item>
                  <el-form-item label="数量" prop="productInventory">
                    <el-input-number v-model="addProduct.productInventory"></el-input-number>
                  </el-form-item>
                  <el-form-item label="立即上架" prop="isSell">
                    <el-switch style="display: block" v-model="addProduct.isSell" active-color="#13ce66" inactive-color="#ff4949">
                    </el-switch>
                  </el-form-item>
                  <el-form-item label="简介" prop="productIntroduce">
                    <el-input type="textarea" resize="false" :rows="3" v-model="addProduct.productIntroduce"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="选择种类" prop="tp">
                    <el-select @change="typeSelect" v-model="tp" filterable remote reserve-keyword placeholder="请输入关键词"
                      :remote-method="remoteMethod" :loading="loading">
                      <el-option v-for="item in typeList" :key="item.typeName" :label="item.typeName" :value="item.typeId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="展示图">
                    <el-upload name="logo" :before-upload="beforeUpload" :data="addProduct" ref="addProductPic" action="http://localhost:8080/product/add"
                      :on-remove="handleRemove" list-type="picture" :on-exceed="onExceed" :limit="1" :auto-upload="false">
                      <el-button type="primary">上传图片</el-button>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitAdd">确 定</el-button>
            </div>
          </el-dialog>
          <!--/ 添加商品模态框 -->
        </el-row>

      </el-col>
      <el-col class="paramsPanel" style="text-align: end;">
        <!-- 自动补齐 -->
        <el-autocomplete @keyup.enter.native="doQueryProducts" style="width: 70%;" size="small" :trigger-on-focus="false"
          popper-class="my-autocomplete" v-model="params.keyword" :fetch-suggestions="querySearch" placeholder="请输入关键字"
          @select="handleSelect">
          <el-button @click="doQueryProducts" slot="prepend" icon="el-icon-search"></el-button>
          <template slot-scope="{ item }">
            <el-tooltip effect="dark" :content="item.productName" placement="left">
              <el-row type="flex" align="middle">
                <div style="text-overflow: ellipsis; overflow: hidden;font-weight: bold;">{{ item.productName }}</div>&emsp;
                <span style="font-size: 12px;color: #aaaaaa;">库存：{{ item.productInventory }}</span>
              </el-row>
            </el-tooltip>
          </template>
        </el-autocomplete>
      </el-col>
    </el-row>
    <el-row class="pagination" style="">
      <el-pagination :background="true" @size-change="handleSizeChange" :page-count="5" @current-change="handleCurrentChange"
        :page-sizes="[10, 25, 50, 70]" :page-size="params.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="params.total" :current-page="params.pageNum">
      </el-pagination>
    </el-row>
    <el-row>
      <!-- 表格 -->
      <el-table @sort-change="sortChange" :data="showProsucts" :row-style="{'background-color': '#F2F6FC'}"
        header-cell-class-name="TableHeader" :cell-style="cellStyle">
        <!-- <el-table-column type="index" /> -->
        <el-table-column type="expand">
          <!-- 详细状态模板 -->
          <template slot-scope="scope">
            <el-row type="flex">
              <el-image class="prodInfoImg" fit="scale-down" :src="'http://localhost:8080/fileDownload/getProductFace?productsLogo='+scope.row.productPicture"
                :preview-src-list="['http://localhost:8080/fileDownload/getProductFace?productsLogo='+scope.row.productPicture]">
              </el-image>
              <el-form class="prodInfo" size="medium" label-position="left" label-width="60px">
                <el-form-item label="商品名">
                  <el-input v-model="scope.row.productName"></el-input>
                </el-form-item>
                <el-form-item label="价格" min="0">
                  <el-input-number :min="0" v-model="scope.row.productPrice"></el-input-number>
                </el-form-item>
                <el-form-item label="库存">
                  <el-input-number :min="0" v-model="scope.row.productInventory"></el-input-number>
                </el-form-item>
                <el-form-item label="简介">
                  <el-input type="textarea" :rows="4" resize="none" v-model="scope.row.productIntroduce"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateProduct(scope.row)">提交修改</el-button>
                </el-form-item>
              </el-form>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="productName" label="商品名"></el-table-column>
        <el-table-column show-overflow-tooltip prop="productInventory" label="库存" width="130" sortable></el-table-column>
        <el-table-column show-overflow-tooltip prop="productPrice" label="价格" width="130" sortable></el-table-column>
        <el-table-column show-overflow-tooltip label="标签">
          <template slot-scope="scope">
            <el-tag :type="scope.row.productStatus===1?'success':'danger'" v-text="scope.row.productStatus===1?'在售':'已下架'"
              size="small" effect="dark"></el-tag>
            <el-tag type="danger" v-if="scope.row.productInventory<50" size="small" effect="dark">库存不足</el-tag>
            <el-tag size="small" type="primary" effect="dark">{{scope.row.type.typeName}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="操作" width="100">
          <template slot-scope="scope">
            <el-button v-text="scope.row.productStatus===1?'下架':'上架'" size="mini" :type=" scope.row.productStatus===1?'danger':'success'"
              @click="handleDelete(scope.$index, scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="pagination" style="">
      <el-pagination :background="true" @size-change="handleSizeChange" :page-count="5" @current-change="handleCurrentChange"
        :page-sizes="[10, 25, 50, 70]" :page-size="params.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="params.total" :current-page="params.pageNum">
      </el-pagination>
    </el-row>
    <!-- <el-backtop target=".page-component__scroll .el-scrollbar__wrap"></el-backtop> -->
  </div>
</template>

<script>
  const axios = require('axios');
  export default {
    name: "productsManager",
    data() {
      return {
        typeList: [],
        tp: '',
        loading: false,
        // 添加商品表单绑定值
        addProduct: {
          typeId: undefined,
          sellerId: this.$store.getters.seller.sellerId,
          productName: '',
          productInventory: 0,
          productPrice: 0,
          isSell: true,
          productStatus: 1,
          productIntroduce: '',
        },
        // 添加商品对话框显示标杆
        dialogFormVisible: false,

        showProsucts: [],
        types: [],
        params: {
          total: undefined,
          pageNum: 1,
          pageSize: 10,
          keyword: '',
          orderBy: '',
          desc: true,
          sellerAccount: this.$store.getters.seller.sellerAccount
        }
      }
    },

    methods: {
      sortChange({
        column,
        prop,
        order
      }) {
        if (order === 'descending') {
          this.params.desc = true
          this.params.orderBy = prop
        } else if (order === 'ascending') {
          this.params.desc = false
          this.params.orderBy = prop
        } else {
          this.params.orderBy = null
        }
        this.doQueryProducts()

      },
      onExceed() {
        this.$message({
          message: "只能选择一张图片",
          type: "error",
          center: true,
          duration: 2000
        })
      },
      beforeUpload(file) {},
      typeSelect(item) {
        this.addProduct.typeId = item
      },
      remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          axios.get("http://localhost:8080/type/types")
            .then(res => {
              this.typeList = res.data
            })
            .catch(err => {})
          setTimeout(() => {
            this.loading = false;
            this.typeList = this.typeList.filter(item => {
              return item.typeName.toLowerCase()
                .indexOf(query.toLowerCase()) > -1;
            });
          }, 200);
        } else {
          this.typeList = [];
        }
      },
      submitAdd() {
        this.productStatus = this.isSell ? 1 : 0
        
        this.dialogFormVisible = false;
        if (this.$refs.addProductPic.$refs['upload-inner'].fileList.length === 0) {
          let data = new FormData()
          for (let i in this.addProduct) {
            data.append(i, this.addProduct[i])
          }
          axios.post("http://localhost:8080/product/add", data)
            .then(res => {
              
            })
            .catch(err => {})
        } else {
          this.$refs.addProductPic.submit();
        }
        this.$refs['addProdForm'].resetFields();
      },
      handleRemove(file, fileList) {
        console.log(file);
      },
      // 查询自动补齐
      querySearch(queryString, cb) {
        this.queryAllProd().then(res => {
          let autoComProducts = res.data.list
          var results = queryString ? autoComProducts.filter(this.createFilter(queryString)) : autoComProducts;
          cb(results);
        })
      },
      // 自动补齐方法
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.productName.toLowerCase().indexOf(queryString.toLowerCase()) !== -1 || restaurant.type.typeName
            .toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
        };
      },
      cellStyle({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        if (columnIndex === 1 || columnIndex === 2 || columnIndex === 3) {
          return 'font-weight: bold;'
        }
      },
      handleSelect(item) {
        this.params.keyword = item.productName
        this.doQueryProducts()
      },
      handleIconClick(ev) {
        console.log(ev);
      },
      doAddProduct() {},
      // 更新商品信息
      updateProduct(product) {
        console.log(product)
      },
      queryAllProd() {
        return axios.get("http://localhost:8080/product/getByPageProduct", {
          params: {
            pageNum: 1,
            pageSize: 500,
            keyword: '',
            sellerAccount: this.$store.getters.seller.sellerAccount
          }
        })
      },
      doQueryProducts() {
        axios.get("http://localhost:8080/product/getByPageProduct", {
          params: this.params
        }).then(res => {
          this.showProsucts = res.data.list
          this.params.total = res.data.total
        }).catch(err => {

        })
      },
      handleSizeChange(val) {
        this.params.pageNum = 1
        this.params.pageSize = val
        this.doQueryProducts()
      },
      handleCurrentChange(val) {
        this.params.pageNum = val
        this.doQueryProducts()
      },
      selectType(commad) {
        console.log(commad)
      },
      handleEdit(index, row) {
        console.log(index, row);
      },
      handleDelete(index, row) {
        console.log(index, row);
      }
    },
    mounted() {
      this.doQueryProducts();
    }
  }
</script>

<style>
  #productsManager {
    background-color: #FFFFFF;
  }

  .TableHeader {
    font-size: 20px;
  }

  #headTitle {
    margin: 5px;
    font-size: 24px;
    font-weight: bold;
    padding: 8px;
    border-radius: 6px;
    background-color: #409EFF;
    color: white
  }

  .pagination {
    z-index: 1;
    text-align: center;
    padding: 10px;
  }

  .prodInfo .el-form-item {
    /* margin: 5px 10px; */
    font-weight: bold;
  }

  .prodInfo {
    width: 100%;
    margin: 0 20px;
  }

  .prodInfoImg {
    height: 400px;
    width: 800px;
    border: #cbcbcb solid 2px;
    border-radius: 6px;
  }

  .header {
    padding: 5px;
    margin: 10px 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
  }

  .paramsPanel {
    margin: 5px;
  }
</style>
